<!--
 * @Date: 2024-07-25 11:26:35
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2024-10-29 09:39:39
 * @Description: 数据字段选择弹窗
-->
<template>
  <vxe-modal
    :="dialogAttrs"
    @close="handleReset"
    v-model="dialogState.visible"
  >
    <VfLayoutFull :="layoutAttrs">
      <template #aside>
        <el-tree
          ref="treeRef"
          node-key="value"
          highlight-current
          default-expand-all
          :data="treeStore.treeData"
          :current-node-key="treeStore.currentValue"
          @node-click="treeNodeClick"
        />
      </template>
      <template #main>
        <VfDataTable ref="tableRef" :="tableAttrs" @radioChange='radioChange'>
            <template #toolbar_left>
              <div class="field-tag">
                <span>当前选择：</span>
                <span>{{ echoSelectField }}</span>
              </div>
            </template>
            <template #toolbar_right>
              <div style="display: flex;">
                <el-input
                  size="default"
                  v-model="tablemParams.keyWords"
                  style="width: 200px;"
                  placeholder="请输入表字段或备注"
                  clearable
                  @change="loadTableData"
                />
              </div>
            </template>
          </VfDataTable>
      </template>
    </VfLayoutFull>
    <template #footer>
      <el-button size="default" type="primary" @click="handleConfirm">确定</el-button>
      <el-button size="default" @click="handleReset">取消</el-button>
    </template>
  </vxe-modal>
</template>

<!-- 数据字段选择弹窗 -->
<script setup name="DataFieldDialog">
import { VfMessage } from '@/utils/vf-utils'
import { VfDataTable } from '@/components/vf-table';
import { VfLayoutFull } from '@/components/vf-layout'
import { ref, reactive, watch, inject, toRaw, nextTick, onBeforeMount, computed } from 'vue'

import { baseAttrs } from '@/components/dialogs/cfg/base-cofig.js'
import { getDataFieldTableList, getDataFieldTableColumns } from '@/api/api-setting'


const emits = defineEmits(['confirm'])

const props = defineProps({
  height: { type: [String, Number], default: 'auto' },
  optionModel: {  type: Object }
})

const axiosConfig = inject('axiosConfig')

// ----- TODO BeforeMount
onBeforeMount(() => { loadTreeData() })

// 布局组件属性
const layoutAttrs = reactive({
  designState: false,
  enableHeader: false,
  upDownEnabled: false,
  mainCondition: {
    enabled: false
  },
})

// ----- TODO 弹窗相关操作
// 弹窗属性配置
const dialogAttrs = reactive({
  ...baseAttrs,
  title: '选择数据字段',
})
// 弹窗数据集
const dialogState = reactive({
  visible: false,
})
// 打开弹窗
function handleOpen () {
  dialogState.visible = true
  const { dataField } = props.optionModel
  if (dataField) {
    const [tableName, tableColumn] = dataField.split('.')
    treeStore.currentValue = tableName
    tableAttrs.radioCacelBtn = false
  } else {
    if (!treeStore.firstTreeNode) return
    treeStore.currentValue = treeStore.firstTreeNode.value
  }
}
// 重置弹窗
function handleReset () {
  dialogState.visible = false
  // 重置树结构数据集
  treeStore.currentValue = ''
  treeStore.firstTreeNode = ''
  // 重置表格相关数据
  tableAttrs.data = []
  tableStore.selectRow = ''
  tablemParams.keyWords = ''
}
// 点击确定
function handleConfirm () {
  const tableCurrentRow = tableRef.value.getRadioRecord()
  if (tableCurrentRow) {
    handleReset()
    emits('confirm', toRaw(tableCurrentRow))
  } else {
    VfMessage.warning('请选择一条记录，进行操作！')
  }
}

// ----- TODO 左侧树结构操作
const treeRef = ref(null)
// 树结构数据集
const treeStore = reactive({
  treeData: [],
  currentValue: '',
  firstTreeNode: [],
})
/**
 * 请求获取树结构数据
 */
const reqTreeData = function () {
  return new Promise(reslove => {
    getDataFieldTableList(axiosConfig.request).then(res => {
      const { code, data } = res
      if (code === 200) {
        const resultData = data.map(item => {
          return { "label": item.name, "value": item.name, "children": [] }
        })
        reslove(resultData)
      } else {
        reslove('')
      }
    }).catch(err => {
      console.error(err)
      reslove('')
    })
  })
}
/**
 * 加载树结构数据
 */
const loadTreeData = async function () {
  const treeData = await reqTreeData()
  if (!treeData) return
  const rootTreeNode = { "label": "全部", "value": "all", "children": [] }
  treeStore.treeData = [ { ...rootTreeNode, children: treeData } ]
  treeStore.firstTreeNode = treeData[0]
}
/**
 * 树节点点击事件
 * 
 * @param nodeObj 树节点数据
 * @param nodeAttr 树参数
 * @param treeNode 树节点
 * @param event 其他
 */
const treeNodeClick = function (nodeObj, nodeAttr, treeNode, event) {
  if (nodeObj.value === 'all'){ return }
  treeStore.currentValue = nodeObj.value
}
watch(
  () => treeStore.currentValue,
  (newValue, oldValue) => {
    if (newValue) {
      tablemParams.tableName = newValue
      loadTableData()
    } else {
      tableAttrs.data = []
    }
  }
)

// ----- TODO 右侧表格相关操作
// 表格Ref对象
const tableRef = ref(null)
// 表格属性
const tableAttrs = reactive({
  data: [],
  loading: false,
  keyField: 'columnCode',
  boxConfig: { mode: 'radio' },
  pagerConfig: false,
  radioConfig: { trigger: 'row', highlight: true },
  radioCacelBtn: true,
  toolbarConfig: { refresh: false },
  columns: [
    { field: 'tableName', title: '表名称' },
    { field: 'columnName', title: '表字段' },
    { field: 'columnComments', title: '备注' }
  ]
})
// 表格数据集
const tableStore = reactive({
  selectRow: ''
})
// 表格查询参数
const tablemParams = reactive({
  tableName: '', keyWords: ''
})
/**
 * 单选选中时触发
 *
 * @param param { row }
 */
const radioChange = (values) => {
  tableStore.selectRow = values ? values.row : ''
}
/**
 * 获取表格数据
 */
const reqTableData = () => {
  return new Promise(resolve => {
    getDataFieldTableColumns(axiosConfig.request, toRaw(tablemParams)).then(res => {
      const { code, data } = res
      if (code === 200) {
        const result = data.map(item => {
          item['columnCode'] = `${item.tableName}.${item.columnName}`
          return item
        })
        resolve(result)
      } else {
        resolve([])
      }
    }).catch(err => {
      console.error(err)
      reslove([])
    })
  })
}
/**
 * 加载表格数据
 */
const loadTableData = async () => {
  tableAttrs.loading = true
  const resultData = await reqTableData()
  tableAttrs.data = resultData
  // 处理选中信息
  const { dataField } = props.optionModel
  const [tableName, columnName] = dataField.split('.')
  tableAttrs.loading = false
  if (!!!dataField) return
  nextTick(() => {
    if (!columnName) return
    const selectRow = tableAttrs.data.find(item => item.columnCode == dataField)
    if (!selectRow) return 
    tableRef.value.setRadioRow(selectRow)
    setTimeout(() => { tableRef.value.scrollToRow(selectRow) }, 300);
  })
}

// 选择的字段回显
const echoSelectField = computed(() => {
  const { dataField } = props.optionModel
  if (tableStore.selectRow) {
    return `${tableStore.selectRow.tableName}.${tableStore.selectRow.columnName}`
  } else {
    return dataField || '暂无'
  }
})

// 对外暴露方法
defineExpose({ handleOpen })

</script>

<style lang="scss" scoped>
.field-tag {
  color: #fff;
  background-color: #3eaf7c;
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 5px;
  font-weight: 600;
  margin-left: 10px;
}
</style>
<style lang="scss">
</style>
